package top.oylan.manager.controller.mp;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.web.bind.annotation.*;
import top.oylan.manager.entity.User;
import top.oylan.manager.entity.mp.MpResult;
import top.oylan.manager.service.UserService;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author abduahad
 * @Description ${description}
 * @Date 2019-08-13
 */
@RestController
@CrossOrigin
@RequestMapping("/mp/auth")
public class MpAuthController {

    @Resource
    UserService userService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public MpResult login(@RequestParam("phone")String phone,
                          @RequestParam("password")String password) {

        MpResult result = new MpResult();

        User user = userService.findUserByPhone(phone);
        if(user == null){
            result.setCode(30);
            result.setMsg("用户不存在");
            return result;
        }
        ByteSource salt = ByteSource.Util.bytes(user.getId().toString());
        SimpleHash simpleHash = new SimpleHash("md5", password, salt, 12);
        if(user.getPassword().equals(simpleHash.toString())){
            result.setMsg("登录成功");
            result.setData(user);
        }else{
            result.setCode(20);
            result.setMsg("密码错误");
        }
        return result;
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public MpResult register(@RequestParam("phone")String phone,
                             @RequestParam("password")String password){
        MpResult result = new MpResult();

        User user = userService.findUserByPhone(phone);
        if(user != null) {
            result.setCode(30);
            result.setMsg("用户已存在");
            return result;
        }
        user = new User();
        user.setType((byte)2);
        user.setPhone(phone);
        user.setPassword(password);
        user.setCreateTime(new Date());
        int res = userService.addUser(user);
        if(res == 0){
            result.setMsg("注册失败");
            result.setCode(20);
        }
        ByteSource salt = ByteSource.Util.bytes(user.getId().toString());
        SimpleHash simpleHash = new SimpleHash("md5", password, salt, 12);
        user.setPassword(simpleHash.toString());
        userService.updateUser(user);
        return result;
    }
}
